package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.dongdong.data.DataResult;
import com.dongdong.data.ResponseStatusEnum;
import com.dongdong.pojo.*;
import com.dongdong.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/13 16:06
 * @Version 1.0
 **/
@Controller
@RequestMapping("goodsController")
public class GoodsController {

    private final Logger logger= LoggerFactory.getLogger(GoodsController.class);

    @Reference
    private GoodsService goodsService;

    @Reference
    private ItemCatService itemCatService;

    @Reference
    private GoodsDescService goodsDescService;

    @Reference
    private TemplateService templateService;

    @Reference
    private TbSpecificationOptionService tbSpecificationOptionService;

    @RequestMapping("list")
    public String list(){
        return "admin/goods_edit";
    }

    @RequestMapping("getItem/{parentId}")
    @ResponseBody
    public DataResult getItem(@PathVariable("parentId") Long parentId){
        try {
            List<TbItemCat> itemCats = itemCatService.getItem(parentId);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(itemCats);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("getTypeId/{typeId}")
    @ResponseBody
    public DataResult getTypeId(@PathVariable("typeId") Long typeId){
        try {
            Long itemCats = itemCatService.getTypeId(typeId);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(itemCats);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("getTemp/{id}")
    @ResponseBody
    public DataResult getTemp(@PathVariable("id") Long id){
        try {
            TbTypeTemplate typeTemplates = templateService.getTemp(id);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(typeTemplates);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("insertGoods")
    @ResponseBody
    public DataResult insertGoods(TbGoods tbGoods, TbGoodsDesc tbGoodsDesc,String itemListJson){
        try {
            Subject subject = SecurityUtils.getSubject();
            TbSeller principal = (TbSeller) subject.getPrincipal();
            String sellerId = principal.getSellerId();
            tbGoods.setSellerId(sellerId);
            String sellerName =principal.getName();
            tbGoods.setAuditStatus("0");
            List<TbItem> list = JSON.parseArray(itemListJson,TbItem.class);
            int i = goodsService.insertGoods(tbGoods,tbGoodsDesc,sellerName,list);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(i);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("upLoadFile")
    @ResponseBody
    public DataResult upLoadFile(@RequestParam(value = "myFile") MultipartFile myFile){
        try{
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = "https://oss-cn-beijing.aliyuncs.com";
            String domain = "oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI4G7eZ5SaEGucGGDSue4a";
            String accessKeySecret = "CCEA89SriqlLlytasVbZ4K11Xwi7ay";
            String bucketName = "l-h";
            // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = myFile.getOriginalFilename();//上传文件的路径

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //String content = "Hello OSS";
            String url = null;//前台路径
            try {
                ossClient.putObject(bucketName, objectName, myFile.getInputStream());
                //拼接图片访问路径
                url = "http://" + bucketName +"."+ domain +"/"+objectName;
                System.out.println(url);

            } catch (IOException e) {
                e.printStackTrace();
                return DataResult.response(ResponseStatusEnum.SUCCESS);
            }

            // 关闭OSSClient
            ossClient.shutdown();
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(url);
        }catch (Exception e){
            logger.info("操作异常",e);
            return DataResult.response(ResponseStatusEnum.SUCCESS);
        }
    }

    @RequestMapping("getSpec/{id}")
    @ResponseBody
    public DataResult getSpec(@PathVariable("id")Long id){
        try {
            //根据id查询到模板表(全部)
            TbTypeTemplate tbTypeTemplate = templateService.getSpec(id);
            //获取到模板表中的关联规格{(id:...,text:...)}
            String specIds = tbTypeTemplate.getSpecIds();
            System.out.println(specIds);
            List<SpecVO> specVOS = JSONObject.parseArray(specIds, SpecVO.class);
            System.out.println(specVOS);
            for (SpecVO spec : specVOS) {
                //根据模板中的规格id找到规格从表中的name
                List<TbSpecificationOption> options = tbSpecificationOptionService.getOptionNameById(spec.getId());
                spec.setOptions(options);
            }
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(specVOS);
        }catch (Exception e){
            logger.error("查询错误");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("toGoods")
    public String toGoods(){
//        List<TbItemCat> tbItemCats = itemCatService.getItems();
//        model.addAttribute("item",tbItemCats);
        return "admin/goods";
    }

    @RequestMapping("GoodsCheck")
    @ResponseBody
    public DataResult GoodsCheck(String goodsName,Integer auditStatus){
        try {
            Subject subject = SecurityUtils.getSubject();
            TbSeller principal = (TbSeller) subject.getPrincipal();
            String sellerId = principal.getSellerId();
            List<TbGoods> tbGoods = goodsService.GoodsCheck(goodsName,auditStatus,sellerId);
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(tbGoods);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("updateStatus")
    @ResponseBody
    public DataResult updateStatus(@RequestParam("ids[]") Long[] ids,String status){
        try {
           goodsService.updateStatus(ids,status);
           return DataResult.response(ResponseStatusEnum.SUCCESS);
        }catch (Exception e){
            logger.error("查询失败",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }
}

